<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 5px">

      <el-input v-model="listQuery.username" placeholder="代理商名字" style="width: 200px;margin-right: 10px"
                class="filter-item"/>
      <el-input v-model="listQuery.field" placeholder="二维码,mac,模组号,imei,卡号" style="width: 200px;margin-right: 10px;" class="filter-item"  />

      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-right: 10px"
          class="filter-item"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"

      >
      </el-date-picker>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="downloadMeterData"
      >
        导出电表
      </el-button>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        导入电表
      </el-button>
    </div>

    <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                       :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="代理商">
        <template slot-scope="{row}">
          <span>{{ row.user ? row.user.name : '未分配' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="二维码编号">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="表号">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="蓝牙Mac地址">
        <template slot-scope="{row}">
          <span>{{ row.mac }}</span>
        </template>
      </el-table-column>

      <el-table-column label="主题(IMEI)">
        <template slot-scope="{row}">
          <span>{{ row.module_no }}</span>
        </template>
      </el-table-column>



      <el-table-column label="物联网卡号">
        <template slot-scope="{row}">
          <span>{{ row.iccid }}</span>
        </template>
      </el-table-column>

      <el-table-column label="总调用次数">
        <template slot-scope="{row}">
          <span>{{ row.call_count }}</span>
        </template>
      </el-table-column>

      <el-table-column label="月调用次数">
        <template slot-scope="{row}">
          <span>{{ row.call_count_month }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后在线时间">
        <template slot-scope="{row}">
          <span>{{ row.read_at }}</span>
        </template>
      </el-table-column>

      <el-table-column label="类型">
        <template slot-scope="{row}">
          <span v-if="row.is_master">4G</span>
          <span v-else>蓝牙</span>
        </template>
      </el-table-column>

      <el-table-column label="导入时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updated_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!--          <el-button size="mini" type="danger" @click="handleDisable(row,$index)">-->
          <!--            禁用-->
          <!--          </el-button>-->
          <el-button size="mini" type="primary" @click="showCallHistoryDialog(row)">
            查看调用流水
          </el-button>
        </template>

      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="getList"
    />
    <el-dialog title="导入电表" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
               style="width: 400px; margin-left:50px;"
      >

        <el-form-item label="用户名或账号" prop="username">
          <el-input v-model="temp.username"/>
        </el-form-item>


        <el-form-item label="csv文件" prop="selectedFile">
          <el-upload
              ref="uploadRef"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept=".csv"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <span v-if="temp.selectedFile">{{ temp.selectedFile.name }}</span>
          </el-upload>
          <el-button style="margin-top:20px"  type="primary" @click="downloadCsvDemo">
            下载电表导入demo.csv
          </el-button>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="电表调用的日流水" :visible.sync="dialogCallHistoryVisible">
      <el-table
          :data="deviceCallList"
          v-loading="listDialogLoading"
          border
          fit
          highlight-current-row
          style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="日期" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.call_date }}</span>
          </template>
        </el-table-column>

        <el-table-column label="总调用次数">
          <template slot-scope="{row}">
            <span>{{ row.call_count }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalDeviceCall>0" :total="totalDeviceCall" :page.sync="listQueryCall.pageNum" :limit.sync="listQueryCall.pageSize"
                  @pagination="getDeviceCallList"
      />
    </el-dialog>


  </div>
</template>

<script>
import {deviceDisable, deviceList,getDeviceCallDayFlow,exportCsv} from '@/api/admin'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {parseTime} from '@/utils'
import {getToken} from '@/utils/auth'
import axios from 'axios';

export default {
  name: 'MeterList',
  components: {Pagination},
  filters: {
    parseTime
  },
  data() {
    return {
      tableKey: 0,
      dialogTagVisible: false,
      dialogCallHistoryVisible: false,
      tagIndex: 0,//tag的索引
      list: null,
      total: 0,
      totalDeviceCall: 0,
      deviceCallList:null,
      listLoading: true,
      listDialogLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        username: undefined,
        sort: '-id',
        field: undefined,
        startDate:undefined,
        endDate:undefined
      },
      listQueryCall: {
        pageNum: 1,
        pageSize: 10,
        mac:null
      },
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      showReviewer: false,
      temp: {
        username: undefined,
        selectedFile: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogPvVisible: false,
      rules: {
        username: [{required: true, message: '请填写用户名', trigger: 'blur'}],
        selectedFile: [{required: true, message: '请选择文件', trigger: 'blur'}]
      },
      importDeviceUrl: '/api/admin/importDevice',
      dateRange:[],

    }
  },
  created() {
    this.getList()
  },
  computed: {
    headers() {
      return {
        'Authorization': 'Bearer' + getToken()
      }
    }
  },
  methods: {
    //设备列表
    getList() {
      this.listLoading = true
      deviceList(this.listQuery).then(response => {

        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getDeviceCallList() {
      this.listDialogLoading = true
      getDeviceCallDayFlow(this.listQueryCall).then(response => {
        this.deviceCallList = response.data.items
        this.totalDeviceCall = response.data.total
        console.log(this.deviceCallList);
        console.log(this.totalDeviceCall)
        this.listDialogLoading = false
      })
    },

    handleFileChange(file) {
      this.temp.selectedFile = file
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        selectedFile: undefined,
        username: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick()
    },
    createData() {
      if (!this.temp.selectedFile) {
        this.$notify({
          title: 'Success',
          message: '请上传文件',
          type: 'success',
          duration: 2000
        })
        return
      }
      console.dir(this.temp)

      // 创建 FormData 对象
      const formData = new FormData();
      formData.append('csv_file', this.temp.selectedFile.raw);
      formData.append('username', this.temp.username)
      // 调用上传接口
      this.uploadFile(formData);

    },
    // 上传文件的方法
    async uploadFile(formData) {
      try {
        // 这里需要替换为你的实际上传接口地址
        const response = await axios.post(this.importDeviceUrl, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'X-token': getToken()
          },
        });
        this.getList()
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: '导入成功',
          type: 'success',
          duration: 2000
        })
        this.$refs.uploadRef.clearFiles()
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
      }
    },
    handleDisable(row, index) {
      deviceDisable(row).then(() => {
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })

    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    showCallHistoryDialog: function (data) {
      this.dialogCallHistoryVisible = true
      this.listQueryCall.pageNum = 1
      this.listQueryCall.mac = data.mac
      this.getDeviceCallList()
      this.$nextTick()
    },
    downloadCsvDemo: function () {
      window.open('/api/admin/downloadDemo');
    },
    downloadMeterData() {
      exportCsv(this.listQuery).then(response =>{
        const csvData = response.data.data;
        const blob = new Blob([csvData], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', response.data.fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      })
    },

    //日期修改
    handleDateChange(value){
      if (value && value.length === 2) {
        this.listQuery.startDate = value[0];
        this.listQuery.endDate = value[1];
      }
    }

  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  display: block;
}
</style>
